#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File    :   StockQuery.py
@Time    :   2022/11/25 17:03:58
@Author  :   youle
@Email   :   a_fly0505@163.com
@Copyright : 侵权必究
'''

from __future__ import annotations
from typing import Any, TypeVar, overload
import psycopg2
import pandas as pd
import numpy as np
import datetime
from core.config import Config
import sys
sys.path.append("..")

query_last_date = '''SELECT date FROM stock_datas.stock_qfq_{} ORDER BY date DESC LIMIT 1;'''
select_sql = '''SELECT id,date,open,close,hight,low FROM stock_datas.stock_qfq_{} ORDER BY date DESC LIMIT {};'''
query_table_exist = '''select count(*) from pg_class where relname = 'stock_qfq_{}';'''

class StockQuery:
    def __init__(self, config: Config) -> None:
        self.config = config
        self.conn = psycopg2.connect(database=config.database,
                                     user=config.user, password=config.password,
                                     host=config.host, port=config.port)
        self.cur = self.conn.cursor()

    def GetAllStock(self) -> list[tuple[Any, ...]]:
        self.cur.execute("SELECT code, sname FROM stock_market.stock")
        datas = self.cur.fetchall()
        return datas

    def GetStockData(self, code: str) -> tuple[pd.DataFrame, bool]:
        #查询表是否存在
        query_sql = query_table_exist.format(code)
        self.cur.execute(query_sql)
        self.conn.commit()
        raw = self.cur.fetchone()
        if raw[0] == 0:
            return pd.DataFrame(), False
        today = datetime.date.today()
        query_sql = query_last_date.format(code)
        self.cur.execute(query_sql)
        self.conn.commit()
        raw = self.cur.fetchone()
        if raw is None:
           return pd.DataFrame(), False
        lastDate = raw[0]
        if (today - lastDate).days > 60:
           return pd.DataFrame(), False

        sql = select_sql.format(code, 3000)
        self.cur.execute(sql)
        df = pd.DataFrame(self.cur.fetchall())
        return df, True
